package org.jeecg.modules.business.service.impl;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import liquibase.util.StringUtil;
import org.apache.commons.beanutils.BeanMap;
import org.flowable.engine.TaskService;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.business.entity.BussContractReviewDes;
import org.jeecg.modules.business.entity.BussContractReviewDesFiles;
import org.jeecg.modules.business.mapper.BussContractReviewDesFilesMapper;
import org.jeecg.modules.business.mapper.BussContractReviewDesMapper;
import org.jeecg.modules.business.service.IBussContractReviewDesFilesService;
import org.jeecg.modules.business.service.IBussContractReviewDesService;
import org.jeecg.modules.flowable.apithird.business.entity.FlowMyBusiness;
import org.jeecg.modules.flowable.apithird.business.mapper.FlowMyBusinessMapper;
import org.jeecg.modules.flowable.apithird.service.FlowCallBackServiceI;
import org.jeecg.modules.flowable.apithird.service.FlowCommonService;
import org.jeecg.modules.flowable.service.IFlowDefinitionService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.*;

/**
 * @Description: 合同评审说明
 * @Author: jeecg-boot
 * @Date: 2024-05-24
 * @Version: V1.0
 */
@Service("contractReviewDesService")
public class BussContractReviewDesServiceImpl extends ServiceImpl<BussContractReviewDesMapper, BussContractReviewDes> implements IBussContractReviewDesService, FlowCallBackServiceI {

    @Autowired
    private BussContractReviewDesMapper bussContractReviewDesMapper;
    @Autowired
    private BussContractReviewDesFilesMapper bussContractReviewDesFilesMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveMain(BussContractReviewDes bussContractReviewDes, List<BussContractReviewDesFiles> bussContractReviewDesFilesList) {
        bussContractReviewDesMapper.insert(bussContractReviewDes);
        if (bussContractReviewDesFilesList != null && bussContractReviewDesFilesList.size() > 0) {
            for (BussContractReviewDesFiles entity : bussContractReviewDesFilesList) {
                //外键设置
                entity.setContractReivewDesId(bussContractReviewDes.getId());
                bussContractReviewDesFilesMapper.insert(entity);
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateMain(BussContractReviewDes bussContractReviewDes, List<BussContractReviewDesFiles> bussContractReviewDesFilesList) {
        bussContractReviewDesMapper.updateById(bussContractReviewDes);

        //1.先删除子表数据
        bussContractReviewDesFilesMapper.deleteByMainId(bussContractReviewDes.getId());

        //2.子表数据重新插入
        if (bussContractReviewDesFilesList != null && bussContractReviewDesFilesList.size() > 0) {
            for (BussContractReviewDesFiles entity : bussContractReviewDesFilesList) {
                //外键设置
                entity.setContractReivewDesId(bussContractReviewDes.getId());
                bussContractReviewDesFilesMapper.insert(entity);
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delMain(String id) {
        bussContractReviewDesFilesMapper.deleteByMainId(id);
        bussContractReviewDesMapper.deleteById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delBatchMain(Collection<? extends Serializable> idList) {
        for (Serializable id : idList) {
            bussContractReviewDesFilesMapper.deleteByMainId(id.toString());
            bussContractReviewDesMapper.deleteById(id);
        }
    }

    @Autowired
    private TaskService taskService;
    @Autowired
    FlowCommonService flowCommonService;

    @Override
    public void afterFlowHandle(FlowMyBusiness business) {
        //流程操作后做些什么
        business.getTaskNameId();//接下来审批的节点
        business.getValues();//前端传进来的参数
        //审批通过
        String actStatus = business.getActStatus();//流程状态 ActStatus.java



//        taskService
        //....其他

    }


    @Override
    public Object getBusinessDataById(String dataId) {
        return this.getById(dataId);
    }

    @Override
    public Map<String, Object> flowValuesOfTask(String taskNameId, Map<String, Object> values) {
        return null;
    }

    @Override
    public List<String> flowCandidateUsernamesOfTask(String taskNameId, Map<String, Object> values) {
        // 通过当前节点来判断下一个节点的候选人并写回到反参中，如果为null，流程模块会根据默认设置处理

        return null;
    }

    @Override
    public IPage<BussContractReviewDes> myPage(Page<BussContractReviewDes> page, QueryWrapper<BussContractReviewDes> queryWrapper) {
        return this.baseMapper.myPage(page, queryWrapper);
    }

    @Override
    public boolean save(BussContractReviewDes contractReviewDes) {
        /**新增数据**/
        contractReviewDes.setId(IdUtil.fastSimpleUUID());
        //Comparison method violates its general contract!有时候出现这个错误加的，原因不明
        System.setProperty("java.util.Arrays.useLegacyMergeSort", "true");
        return super.save(contractReviewDes);
    }

    @Override
    public boolean removeById(Serializable id) {
        /**删除数据，移除流程关联信息**/
        flowCommonService.delActBusiness(id.toString());
        bussContractReviewDesFilesMapper.deleteByMainId(String.valueOf(id));
        return super.removeById(id);
    }

    @Override
    public boolean removeByIds(Collection<?> list) {
        /**删除数据，移除流程关联信息**/
        for (Object id : list) {
            flowCommonService.delActBusiness(id.toString());
            bussContractReviewDesFilesMapper.deleteByMainId(String.valueOf(id));
        }

        return super.removeByIds(list);
    }

    @Autowired
    private IBussContractReviewDesFilesService bussContractReviewDesFilesService;

    @Autowired
    private IFlowDefinitionService flowDefinitionService;

    @Autowired
    private FlowMyBusinessMapper flowMyBusinessMapper;

    @Override
    public Result reverseCheck(String id){
        BussContractReviewDes bussContractReviewDes = this.getById(id);
        if (bussContractReviewDes == null) {
            return Result.error("未找到对应数据");
        }
        BussContractReviewDes copyDes = new BussContractReviewDes();
        BeanUtils.copyProperties(bussContractReviewDes, copyDes);
        List<BussContractReviewDesFiles> list = bussContractReviewDesFilesService.list(new LambdaQueryWrapper<BussContractReviewDesFiles>().eq(BussContractReviewDesFiles::getContractReivewDesId, copyDes.getId()));

        copyDes.setCreateTime(null);
        copyDes.setUpdateTime(null);
        copyDes.setUpdateBy(null);
        copyDes.setCreateBy(null);
        this.save(copyDes);
        if (CollectionUtil.isNotEmpty(list)) {
            list.stream().forEach(f -> {
                f.setId(null);
                f.setCreateTime(null);
                f.setUpdateTime(null);
                f.setUpdateBy(null);
                f.setCreateBy(null);
            });
        }
        bussContractReviewDesFilesService.saveBatch(list);
        String dataId = copyDes.getId();
        BeanMap variables = new BeanMap(copyDes);
        FlowMyBusiness flowMyBusiness = flowMyBusinessMapper.selectOne(new LambdaQueryWrapper<FlowMyBusiness>().eq(FlowMyBusiness::getDataId, id).last(" limit 1"));
        if (Objects.isNull(flowMyBusiness)) {
            return Result.error("该表单尚未发起审批,不可以发起反审核操作");
        }
        String actStatus = flowMyBusiness.getActStatus();
        if (!"审批通过".equals(actStatus)) {
            return Result.error("只有审批通过的表单可以发起反审核操作");
        }
        // 转换为 Map<String, Object>
        Map<String, Object> map = new HashMap<>();
        for (Object key : variables.keySet()) {
            map.put((String) key, variables.get(key));
        }
        map.put("dataId", dataId);
        return flowDefinitionService.startProcessInstanceByDataId(dataId, "contractReviewDesService", map);
    }

}
